package com.luoguijia.disk.share.control;

import com.alibaba.fastjson.JSON;
import com.luoguijia.disk.files.service.FileService;
import com.luoguijia.disk.mybatis.entity.PtFileEntity;
import com.luoguijia.disk.mybatis.entity.PtShareEntity;
import com.luoguijia.disk.mybatis.flexigrid.PagingEntity;
import com.luoguijia.disk.mybatis.flexigrid.TblResponseEntity;
import com.luoguijia.disk.mybatis.ztree.ZtreeEntity;
import com.luoguijia.disk.share.entity.SearchShareEntity;
import com.luoguijia.disk.share.service.ShareService;
import com.luoguijia.disk.spring.control.BaseController;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

@Controller
@RequestMapping("/share")
public class ShareController extends BaseController {

    @Resource
    private ShareService shareService;

    @Resource
    private FileService fileService;

    @GetMapping("/mysharePage")
    public String sharePage() {
        return "share/mysharePage";
    }

    @Secured("ROLE_cldk_data_share")
    @RequestMapping("/queryShareInfoListByPage")
    @ResponseBody
    public TblResponseEntity<PtShareEntity> queryShareInfoListByPage(SearchShareEntity entity, PagingEntity paging) {
        return shareService.queryShareInfoListByPage(entity, paging);
    }

    @Secured("ROLE_cldk_data_share_mod")
    @RequestMapping("/queryShareInfoById")
    @ResponseBody
    public PtShareEntity queryShareInfoById(@RequestParam("shareUuid") String shareUuid) {
        return shareService.queryShareInfoById(shareUuid);
    }

    @Secured("ROLE_cldk_data_share_mod")
    @RequestMapping("/modifyShareInfoById")
    @ResponseBody
    public String modifyShareInfoById(PtShareEntity entity) {
        shareService.modifyShareInfoById(entity);
        return successJson("modify.share.success");
    }

    @Secured("ROLE_cldk_data_share_add")
    @RequestMapping("/addShareInfoById")
    @ResponseBody
    public String addShareInfoById(PtShareEntity entity) {
        shareService.addShareInfoById(entity);
        return successJson("add.share.success");
    }

    @Secured("ROLE_cldk_data_share_del")
    @RequestMapping("/deleteShareByIds")
    @ResponseBody
    public String deleteShareByIds(@RequestParam("ids") String ids) {
        shareService.deleteShareByIds(ids);
        return successJson("delete.share.success");
    }

    @Secured("ROLE_cldk_data_share_file")
    @RequestMapping("/queryFileTreeListByShare")
    @ResponseBody
    public List<ZtreeEntity> queryFileTreeListByShare(@RequestParam("shareUuid") String shareUuid) {
        return shareService.queryFileTreeListByShare(shareUuid);
    }

    @Secured("ROLE_cldk_data_share_file")
    @RequestMapping("/saveShareRefFile")
    @ResponseBody
    public String saveShareRefFile(@RequestParam("shareUuidArray") String shareUuidArray,
                                 @RequestParam("fileIdArray") String fileIdArray) {
        shareService.saveShareRefFile(shareUuidArray, fileIdArray);
        return successJson("share.allocate.file.success");
    }

    /**
     * 通过分享链接访问文件
     * @param code 分享码
     * @return 文件内容或下载链接
     */
    @GetMapping("/access")
    public ResponseEntity<?> accessShare(@RequestParam("code") String code) {
        try {
            // 1. 根据分享码查询分享信息
            // 注意：这里需要在ShareService中添加根据分享码查询的方法
            PtShareEntity shareEntity = shareService.queryShareByCode(code);
            if (shareEntity == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body("分享链接不存在或已失效");
            }

            // 2. 检查分享是否过期
            if (shareEntity.getExpireTime().before(new Date())) {
                return ResponseEntity.status(HttpStatus.GONE)
                        .body("分享链接已过期");
            }

            // 3. 检查分享状态
            if (shareEntity.getStatus() != 1) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                        .body("分享链接已被禁用");
            }

            // 4. 获取文件信息
            PtFileEntity file = fileService.getFileById(shareEntity.getFileId().toString());
            if (file == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body("分享的文件不存在");
            }

            // 5. 返回文件内容或下载链接
            // 这里简化处理，实际应用中可能需要根据文件类型决定是在线预览还是下载
            Map<String, Object> result = new HashMap<>();
            result.put("fileId", file.getFileUuid());
            result.put("fileName", file.getFileName());
            result.put("fileSize", file.getFileCapacity());
            result.put("fileType", file.getFileType());
            result.put("downloadUrl", "/file/download/" + file.getFileUuid());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("访问分享文件失败: " + e.getMessage());
        }
    }
}
